/**
 * Created by Myron on 2015/9/10.
 */
var async = require('async');
var config = require('../config.js');
var signDayM = require('../models/signday.js');
var singDays = require('signfunc');
var signService = require('../models/signservice.js');
module.exports = {
    //点击购物车按钮进入购物车
    index: function (req, res) {
        var uid = req.AV.user.id;
        //console.log(uid);
        //console.log(global.initData.signGifts);
        res.render('activity/signday1', {title: '每日签到'});
    },
    //进入页面获取数据
    getSignDayValueAjax:function(req, res){
        var uid = req.AV.user.id;
        async.waterfall([
            function(callback){
               //获取用户积分
                signDayM.get_UserInfo(uid).then(function(data){
                    callback(null, data.get('point'));
                }).catch(function(){
                    callback(null, 0)
                });
            },
            function(point,callback){
                //获取用户积分
                signDayM.getUserInfo(uid).then(function(data){
                    callback(null, point,data.get('firstSignDate'));
                }).catch(function(error){
                    callback(null, 0)
                });
            },
            function(point,firstSignDate, callback) {
                var lastSignDate = new Date(new Date(firstSignDate).getTime()+365*24*60*60*1000);
                signDayM.getSignDayValue(uid).then(function(result){
                    callback(null,{code:result.code,MonthSignDay:result.MonthSignDay,AllSignDay:result.AllSignDay,AllSignDays:result.AllSignDays,SignState:result.SignState,GiftArray:result.GiftArray ,point:point,firstSignDate:firstSignDate,lastSignDate:lastSignDate});
                }).catch(function(result){
                    callback(null,{code:result.code,MonthSignDay:result.MonthSignDay,AllSignDay:result.AllSignDay,AllSignDays:result.AllSignDays,SignState:result.SignState,GiftArray:result.GiftArray ,point:point,firstSignDate:firstSignDate,lastSignDate:lastSignDate});
                });
            }
        ], function (err, result) {
            res.json(result);
        });
    },
    getRules:function(req, res){
        signDayM.getSignDayRules().then(function(result){
            res.json({supply:result,sign:global.initData.signGifts});
        });
    },
    //获取签到历史数据
    getSignDayDetailAjax:function (req, res) {
        var month = req.query.Month;
        var year = req.query.Year;
        var uid = req.AV.user.id;
        signDayM.getSignDayDetail(uid,year,month).then(function(result){
            res.json(result);
        });
    },
    //签到操作接口
    setSignDayActionAjax:function (req, res) {
        var uid = req.AV.user.id;
        //console.log('签到');
        async.waterfall([
            function(callback){
                signDayM.setSignDayAction(uid,new Date()).then(function(result){
                    //console.log("签到成功");
                    callback(null, {code:0,results:result});
                }).catch(function(result){
                    callback(null, {code:0,results:result});
                });
            },
            function(signSuccess,callback){
                if(signSuccess.code === 0){
                    signDayM.givePoint(uid,10).then(function(res){
                        callback(null,signSuccess);
                    });
                }
            },
            function(signSuccess,callback){
                //获取当前累计签到天数
                signDayM.getAllSignDays(uid).then(function(data){
                    //console.log("获取累计签到天数成功");
                    if(data){
                        callback(null, data.get('AllSignDays'));
                    }else{
                        callback(null, 0);
                    }
                }).catch(function(){
                    callback(null, 0);
                });
            },
            function(allSignDays,callback){
                var level = '';
                if(allSignDays>=90){
                    //当累计签到大于90天时执行判断是否连续
                    //首先整理出签到详情
                    signDayM.getAllSignDaysDetail(uid).then(function(data){
                        if(data.code===0){
                            var now = new Date();
                            var days = singDays.getDays(data.signMonth,{year:parseInt(now.getFullYear()),month:parseInt(now.getMonth()+1),day:parseInt(now.getDate())});
                            if(days === 90){
                                level = 'D90' ;
                            }else if(days === 180){
                                level = 'D180'
                            }
                            callback(null, {level:level,allSignDays:allSignDays});

                        }
                    }).catch(function(err){
                        console.log(err);
                        callback(null, {level:level,allSignDays:allSignDays});
                    });

                }else{
                    callback(null, {level:level,allSignDays:allSignDays});
                }
            },
            function(allsigndays,callback){
                //获取奖品等级
                if(allsigndays.level === ''){
                    //不满足连续签到
                    signDayM.getGiftLevel(allsigndays.allSignDays).then(function(res){
                        //console.log("获取等级成功");
                        if(res.code === 0){
                            //console.log('累计签到，发放奖品');
                            if(res.level === 'D90' || res.level === 'D180'){
                                callback(null,{code:-1,hasGift:1,level:res.level,AllSignDays:allsigndays.allSignDays});
                            }else{
                                callback(null,{code:0,hasGift:1,level:res.level,AllSignDays:allsigndays.allSignDays});
                            }
                        }else{
                            //console.log('未累计签到，不发放奖品');
                            callback(null,{code:0,hasGift:0,level:res.level,AllSignDays:allsigndays.allSignDays});
                        }
                    });
                }else{
                    callback(null,{code:0,hasGift:1,level:allsigndays.level,AllSignDays:allsigndays.allSignDays});
                }
            },
            //发放奖品
            function(gifts,callback){
                if(gifts.code === 0){
                    var level = gifts.level ;
                    var action = global.initData.signGifts[level].action;
                    if(gifts.hasGift === 1){
                        //发放奖品
                        signService.getGifts(level,uid,action).then(function(data){
                            if(data.code === 0){
                                //发放成功
                                //console.log('发放成功');
                                callback(null, {code:0,hasGift:gifts.hasGift,level:level,AllSignDays:gifts.AllSignDays});
                            }else{
                                //发放失败
                                //console.log('发放失败');
                                callback(null, {code:1,hasGift:gifts.hasGift,level:level,AllSignDays:gifts.AllSignDays});
                            }
                        }).catch(function(){
                            callback({code:1011});
                        });
                    }else{
                        //签到成功，不发放奖品
                        //console.log('签到成功，不发放奖品');
                        callback(null,{code:0,hasGift:0,level:level,AllSignDays:gifts.AllSignDays});
                    }
                }else{
                    callback(null, gifts);
                }
            }
        ],function(err,results){
            if(err){
                //console.log(err);
                res.json(err);
            }else{
                console.log(results);
                res.json(results);
            }
        });
    },
    //领取奖品
    getGift11111:function(req,res){
        var level=req.query.level;
        //console.log('签到礼物等级：'+level);
        var uid = req.AV.user.id;
        var action = global.initData.signGifts[level].action;
        //console.log(action);
        //var action = global.initData.signGift.level.action ;
        async.auto({
            //判断是否领取过
            isGiven:function(callback){
                signDayM.isRecievedGifts(uid,level).then(function(data){
                    //console.log('====getGift====isGiven========');
                    if(data === 2 ){
                        //未领取过
                        callback(null,{code:0});
                    }else{
                        //已领取过，不发放
                        return callback({code:9999});
                    }
                });
            },
            giveGift:['isGiven',function(callback){
                if(results.isGiven.code === 9999){
                    //console.log('====getGift====giveGift========');
                    return callback({code:9999});
                }
                if(parseInt(action.limitMoney)!=-1){
                    //满减，获取cutMoney，执行满减方法
                    var limitMoney = parseInt(action.limitMoney) ;
                    var cutMoney = parseInt(action.cutMoney);
                    signDayM.giveMJ(uid,limitMoney,cutMoney).then(function(data){
                        callback(null, {code:0,msg:data.msg});
                    }).catch(function(err){
                        callback(null, {code:1,msg:""});
                    });
                }else if(parseInt(action.realMoney) != -1){
                    var realMoney = parseInt(action.realMoney);
                    //执行优惠劵
                    signDayM.giveCoupons(uid,realMoney).then(function(data){
                        callback(null, {code:0,msg:data.msg});
                    }).catch(function(err){
                        callback(null, {code:1,msg:""});
                    });
                }else if(parseInt(action.point) != -1){
                    var point = parseInt(action.point);
                    //执行发放积分
                    signDayM.givePoint(uid,point).then(function(data){
                        callback(null, {code:0,msg:data.msg});
                    }).catch(function(err){
                        callback(null, {code:1,msg:""});
                    });
                }else if(parseInt(action.gifts) != -1){
                    //执行发放礼品卷
                    signDayM.giveGiftToCart(uid,level).then(function(data){
                        callback(null, {code:0,msg:data.msg});
                    }).catch(function(err){
                        callback(null, {code:1,msg:""});
                    });
                }else if(parseInt(action.cash) != -1){
                    var cash = parseInt(action.cash);
                    //执行发放现金
                    signDayM.giveCash(uid,cash).then(function(data){
                        callback(null, {code:0,msg:data.msg});
                    }).catch(function(err){
                        callback(null, {code:1,msg:""});
                    });
                }else{
                    //其他特殊情况
                    callback(null, {code:0,msg:data.msg});
                }
            }],
            updateGiveFlow:['giveGift',function(callback,results){
                var isReceived = 0 ;
                if(results.giveGift.code === 0){
                    isReceived = 1 ;
                }
                signDayM.updateGive(uid,level,isReceived).then(function(data){
                    //console.log('更新礼物流水表成功');
                    callback(null, data);
                })
            }]
        },function(err,results){
            if(err){
                //console.log(err)
                res.json(err);
            }else{
                res.json(results.updateGiveFlow);
            }
        });
    },
    getLevelOfBQ:function(req,res){
        var date=req.query.date;
        var uid = req.AV.user.id;
        signDayM.getLevelOfBQ(uid,date).then(function(data){
            //返回一个point
            res.json(data);
        });
    },
    cutPointOfBQ:function(req,res){
        var point=req.query.point;
        var uid = req.AV.user.id;
        signDayM.cutPointOfBQ(uid,point).then(function(data){
            //返回一个point
            res.json(data);
        });
    },
    signDaySupply:function(req,res){
        var uid = req.AV.user.id;
        var date = req.query.date;
        var point = req.query.point ;
        async.auto({
            //获取用户信息
            getUserInfo:function(callback){
                //console.log('success========getUserInfo======');
                signDayM.getUserInfo(uid).then(function(uInfo){
                    if(uInfo){
                        callback(null, {code:0,userInfo:uInfo});
                    }else{
                        callback({code:-1,msg:'还没有签到过，不能补签'})
                    }
                }).catch(function(){
                    callback({code:-1,msg:'网络故障了，稍后再试'})
                });
            },
            //判断是日期是否在同一个周期内
            isInOneSize:['getUserInfo',function(callback,results){

                //console.log('success========isInOneSize======');
                if(results.getUserInfo.code === 0){
                    var days = Math.floor((new Date(new Date(date).toDateString()) - new Date(results.getUserInfo.userInfo.get('firstSignDate').toDateString()))/(24*3600*1000));
                    if(days<=365 && days>=0){
                        callback(null);
                    }else{
                        return callback({code:100,msg:'不再同一个周期内，不能补签哦'+days});
                    }
                }else{
                    return callback({code:100,msg:'没有获取到用户信息'});
                }
            }],
            //开始签到
            signDayAction:['isInOneSize',function(callback){
                signDayM.setSignDayActionSupply(uid,new Date(date)).then(function(data){
                    if(data.code===0){
                        callback(null, {code:0});
                    }else{
                        callback(null, {code:1});
                    }
                }).catch(function(err){
                    return callback(err);
                });
            }],
            cutPoint:['signDayAction',function(callback,results){
                if(results.signDayAction.code === 0){
                    signDayM.cutPointOfBQ(date,uid,point).then(function(data){
                        if(data.code === 0){
                            callback(null, {code:0});
                        }else{
                            callback(null, {code:1});
                        }
                    }).catch(function(err){
                        return callback({code:100,msg:'扣减积分出错了1'});
                    });
                }else{
                    return callback({code:100,msg:'扣减积分出错了2'});
                }
            }],
            givePoint:['cutPoint',function(callback,results){
                if(results.signDayAction.code === 0 &&　results.cutPoint.code === 0){
                    signDayM.givePoint(uid,10).then(function(res){
                        callback(null)
                    });
                }
            }],
            getAllSignDaysAlways:['givePoint','getUserInfo',function(callback,results){
                if(results.getUserInfo.code === 0){
                    var allDays = parseInt(results.getUserInfo.userInfo.get('AllSignDays'))+1 ;
                    var level = '' ;
                    if(allDays >= 90){
                        //判断是否连续
                        signDayM.getAllSignDaysDetail(uid).then(function(data){
                            if(data.code===0){
                                var now = new Date(date);
                                var days = singDays.getDays(data.signMonth,{year:parseInt(now.getFullYear()),month:parseInt(now.getMonth()+1),day:parseInt(now.getDate())});
                                if(days >= 90 && days <= 180){
                                    level = 'D90' ;
                                }else if(days >= 180){
                                    level = 'D180'
                                }
                                callback(null, level);
                            }
                        }).catch(function(err){
                            callback(null, 0);
                        });
                    }else{
                        callback(null, level);
                    }
                }else{
                    return callback({code:1002});
                }
            }],
            getGiftsLevel:['givePoint','getUserInfo',function(callback,results){
                if(results.getUserInfo.code === 0){
                    signDayM.getGiftLevel(parseInt(results.getUserInfo.userInfo.get('AllSignDays'))+1).then(function(level){
                        callback(null,level.level);
                    }).catch(function(err){

                    });
                }
            }],
            //判断是否满足发放礼物要求
            canGiveGift:['getGiftsLevel','getAllSignDaysAlways',function(callback,results){
                if(results.getAllSignDaysAlways === ''){
                    //不符合，不是连续签到
                    if(results.getGiftsLevel === 'D90' || results.getGiftsLevel === 'D180'){
                        //提示非连续签到，需要补签
                        callback(null, {code:-2,msg:'非连续签到，需要补签'});
                    }else{
                        //连续签到，满足90，180天
                        if(results.getGiftsLevel === 0){
                            //不满足要求
                            callback(null, {code:1,level:0,msg:'不满足连续签到，且不满足累计签到'})
                        }else{
                            //满足要求
                            //判断是否发放过礼物
                            signDayM.isRecievedGifts(uid,results.getGiftsLevel).then(function(data){
                                if(data.code === 2){
                                    //未领取过,可以发放礼物
                                    callback(null, {code:0,level:results.getGiftsLevel});
                                }else{
                                    //已领取
                                    callback(null, {code:1});
                                }
                            });
                        }
                    }
                }else{
                    signDayM.isRecievedGifts(uid,results.getAllSignDaysAlways).then(function(data){
                        if(data.code === 2){
                            //未领取过,可以发放礼物
                            callback(null, {code:0,level:results.getAllSignDaysAlways});
                        }else{
                            //已领取
                            callback(null, {code:1,level:results.getAllSignDaysAlways});
                        }
                    });
                }
            }],
            giveGifts:['canGiveGift',function(callback,results){
                if(results.canGiveGift.code === 0){
                    var level = results.canGiveGift.level ;
                    var action = global.initData.signGifts[level].action;
                    signService.getGifts(level,uid,action).then(function(data){
                        if(data.code === 0){
                            //发放成功
                            callback(null, {code:0,level:level});
                        }else{
                            //发放失败
                            callback(null, {code:1,level:level});
                        }
                    }).catch(function(){
                        callback({code:1011,msg:'发放礼物出错了'});
                    });
                }else if(results.canGiveGift.code === -2){
                    //未满足连续签到，不发放礼物
                    callback(null, {code:-2,msg:'非连续签到，需要补签'});
                }else if(results.canGiveGift.code === 1){
                    //已领取
                    callback(null, {code:1,level:level});
                }else{
                    callback({code:1011});
                }
            }]
        },function(err,results){
            if(err){
                res.json(err);
            }else{
                res.json(results.giveGifts);
            }
        });
        //首先判断这一天是否签到
        //其次判断签到是否成功
        //再判断积分是否扣减成功
        //最后判断礼品是否满足规则，并且是否领取过，如果领取过就不发放，没有领取过就发放一遍
    },
    //判断礼品是否领取完成
    isSigndayTody:function(req,res){
        var uid = req.AV.user.id;
        //res.json(uid);
        signDayM.getSignDayValue(uid).then(function(result){
            if(result.code == 1003){
                //首次签到
                res.json({code:0,SignState:0,AllSignDays:0});
            }else{
                res.json({code:result.code,SignState:result.SignState,AllSignDays:result.AllSignDays});
            }
        }).catch(function(result){
            if(result.code == 1003){
                //首次签到
                res.json({code:0,SignState:0,AllSignDays:0});
            }else{
                res.json({code:result.code,SignState:result.SignState,AllSignDays:result.AllSignDays});
            }
        });
    }
}